<?php

namespace App\Models;

use App\Http\Controllers\Resource\ZwzxController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/*数字资源（中文在线）model*/

class ResourceZwzx extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_zwzx';

    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom'
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();
        if ($res) {
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
        }
        return $res;
    }

    /**
     * 添加数据到数据库
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['shId'])) {
            return false;
        }

        $categorys = !empty($data['categorys']) ? trim($data['categorys'], ';') : ''; //数据多了一个分号
        $big_type_id = 1; //固定是电子书类型
        $type_id = null;
        if (!empty($categorys)) {
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $type_data['name'] = $categorys; //类型名称
            $type_data['resource_business_id'] = 1;
            $type_data['big_type_id'] = 1;
            $type_id = $resourceTypeExternalModel->getTypeNameNoAdd($type_data);
        }
        $res = $this->where('data_unique_id', $data['shId'])->first(); //sh_id 区分大小写检索     数据库对应，数据字段 设置为 varbinary 也可以
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        //  else {
        //     Log::channel('escmdlog')->debug('遇到相同数据' . $data['shId']);
        //     Log::channel('escmdlog')->debug($data);
        //     Log::channel('escmdlog')->debug($res->toArray());
        //     die;
        // }
        $res->sh_id = $data['shId'];
        $res->resource_business_id = 1; //固定1，中文在线
        $res->title = $data['name']; //固定1，中文在线
        $res->big_type_id = $big_type_id;
        $res->type_id = $type_id;
        $res->img = str_replace('http://', 'https://', $data['coverImgUrl']);
        $res->link = str_replace('http://', 'https://', $data['coverImgUrl']);
        $res->intro = $data['intro'];
        $res->author = $data['author'] ? $data['author'] : $data['authorPseudonym'];
        $res->isbn = str_replace('-', '', $data['isbn']);
        $res->press = $data['publisher'];
        $res->pre_time = $data['publishDate'];
        $res->assets_id = $data['assetsId'];
        $res->unique_id = $data['uniqueId'];
        $res->first_letter = $data['firstLetter'];
        $res->score = $data['score'];
        $res->category_ztf = $data['categoryZtf'];
        $res->categorys = $categorys;
        $res->storage_date = $data['storageDate'];
        $res->expire = $data['expire'];
        $res->status = $data['status'];
        $res->status_time = $data['statusTime'];
        $res->create = $data['create'];
        $res->modify = $data['modify'];
        $res->edition = $data['edition'];
        $res->translator = $data['translator'];
        $res->topic_words = $data['topicWords'];
        $res->series_name = $data['seriesName'];
        $res->author_pseudonym = $data['authorPseudonym'];
        $res->publish_place = $data['publishPlace'];
        $res->languages = $data['languages'];
        $res->default_type = $data['defaultType'];
        $res->resource_list = $data['resourceList'];
        $res->book_assets = $data['bookAssets'];
        $res->book_authorize_info = $data['bookAuthorizeInfo'];
        $res->data_unique_id = $data['shId']; //数据唯一id
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->addData($res);

        return $res->id;
    }

    /**
     * 获取图书目录
     * @param guid  资源guid
     */
    public function getBookCatalogue($guid)
    {
        $key = md5('getZwzxBookCatalogue-' . $guid);
        $res = Cache::get($key);
        if (empty($res)) {
            $book_info = $this->select('sh_id', 'default_type')->where('guid', $guid)->where('is_del', 1)->first();
            $book_sh_id = trim($book_info['sh_id']);
            $book_type = trim($book_info['default_type']);
            if (empty($book_sh_id) || empty($book_type)) {
                return false;
            }
            $zwzxObj = new ZwzxController();
            $res = $zwzxObj->getBookCatalogue($book_sh_id, $book_type); //计算总条数
            if ($res) Cache::set($key, $res, 24 * 60 * 60); //缓存一天
        }
        return $res['list'] ?? null;
    }

    /**
     * 获取图书阅读地址，单点登录进行阅读
     * @param user_id  用户id  实际是用户token
     * @param guid  资源guid
     */
    public function getZwzxSingleSign($user_id, $guid)
    {
        $book_info = $this->select('sh_id', 'default_type')->where('guid', $guid)->where('is_del', 1)->first();
        if (empty($book_info)) {
            return false;
        }
        $book_sh_id = trim($book_info['sh_id']);
        $book_type = trim($book_info['default_type']);
        if (empty($book_sh_id) || empty($book_type)) {
            return false;
        }
        $zwzxObj = new ZwzxController();
        $res = $zwzxObj->singleSign($user_id, $book_sh_id, $book_type);

        return $res;
    }
}
